/*
   Copyright (c) 2011 Mizar Tools Contributors (mizartools.org)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
/*  Contributors :
 *	2011-04-03 Marco Riccardi - initial implementation
 *  
 */
package org.mizartools.example.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Calendar;
import java.util.LinkedList;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.mizartools.example.test.FileWork;
import org.mizartools.system.Article;
import org.mizartools.system.ArticleFactory;
import org.mizartools.system.EnvironFile;
import org.mizartools.system.ListArticleFile;
import org.mizartools.system.WorkFileExtension;
import org.mizartools.system.executable.ExecutableException;
import org.mizartools.system.executable.MakeEnvironment;
import org.mizartools.system.executable.Verifier;
import org.mizartools.utility.TemporaryDirectory;
import org.mizartools.utility.TemporaryDirectoryException;
import org.mizartools.utility.TemporaryDirectoryFactory;
import org.mizartools.utility.UtilityFile;

@SuppressWarnings("serial")
public class TestMMLPanel extends JPanel {

	private JTextArea textArea;
	private JScrollPane scroller;
	private JPanel progressBarPanel;
	private JProgressBar progressBarMML;
	private JProgressBar progressBarVerifier;
	private JButton button;
	private TestFrame testFrame;

	public TestMMLPanel(TestFrame testFrame){
		super();
		this.testFrame = testFrame;
    	setLayout(new BorderLayout());
		setPreferredSize(new Dimension(500, 150));
		button = new JButton();
		AbstractAction action =  new AbstractAction() { 
	 	    public void actionPerformed(ActionEvent e) {
	 	    	textArea.setText(Calendar.getInstance().getTime().toString()+"\n\n");
	 	    	TestMMLPanel.Job job = new TestMMLPanel.Job();
	 			Thread thread = new Thread(job);
	 			thread.start();
	 	    } 
	 	}; 
	 	button.setAction(action);
	 	button.setMaximumSize(getMaximumSize());
	 	button.setText("Start");
		add(button, BorderLayout.NORTH);
		textArea = new JTextArea();
		textArea.setEditable(false);
        scroller = new JScrollPane();
		scroller.getViewport().add(textArea);
		add(scroller, BorderLayout.CENTER);
		
		progressBarPanel = new JPanel();
		progressBarPanel.setLayout(new BorderLayout());
		progressBarVerifier = new JProgressBar();
		progressBarPanel.add(progressBarVerifier, BorderLayout.NORTH);
		progressBarMML = new JProgressBar();
		progressBarPanel.add(progressBarMML, BorderLayout.SOUTH);
		add(progressBarPanel,BorderLayout.SOUTH);
	}
	
	private class Job implements Runnable {

		private String mmlPath = EnvironFile.getMIZFILES() + File.separator + "mml";
		
		@Override
		public void run() {
			button.setEnabled(false);
			TemporaryDirectory temporaryDirectory = null;
			long beforeTime = Calendar.getInstance().getTimeInMillis() - 24*60*60*1000;
			TemporaryDirectoryFactory.clearTemporaryDirectories(beforeTime);
			try {
				temporaryDirectory = TemporaryDirectoryFactory.newTemporaryDirectory();
			} catch (TemporaryDirectoryException e) {
				textArea.append(e.getMessage());
			}
			if (temporaryDirectory == null){
	    		textArea.append("\n");
	    		textArea.repaint();
	    		textArea.setCaretPosition(textArea.getText().length()-1);
	    		return;
			}
			File workDirectory = temporaryDirectory.getFile();
			textArea.append("Temporary Directory : " + workDirectory.getPath());
			textArea.append("\n");
			textArea.repaint();
			textArea.setCaretPosition(textArea.getText().length()-1);
			LinkedList<String> articleList = ListArticleFile.getArticleList();
	    	progressBarMML.setMaximum(articleList.size()+1);
	    	progressBarMML.setValue(0);
	    	progressBarMML.setIndeterminate(false);
	    	progressBarVerifier.setMaximum(100);
	    	progressBarVerifier.setValue(0);
			progressBarVerifier.setIndeterminate(false);
	    	Article article = null;
	    	String articleName = null;
	    	String fileName = null;
	    	int progress = 0;
	    	long duration = 0;
	    	WorkFileExtension[] wfe = WorkFileExtension.values();
			try {
				String check;
				boolean error = false;
		    	for (String aid : articleList){
		    		if (progress++ < 0) continue;
		    		if (!error){
		    			temporaryDirectory.clear();
			    		article = ArticleFactory.getInstance().getArticle(aid);
			    		articleName = article.getAid().toLowerCase();
						textArea.append((articleName+"["+progress+"]"+"        ").substring(0,14)+" : ");
			    		textArea.repaint();
			    		textArea.setCaretPosition(textArea.getText().length()-1);
						File sourceFile = new File(mmlPath, articleName+".miz");
						File destinationFile = new File(workDirectory, articleName+".miz");
						error = !UtilityFile.Copy(sourceFile, destinationFile);
						if (!error) {
							textArea.append("[MakeEnvironment] ");
				    		textArea.repaint();
				    		textArea.setCaretPosition(textArea.getText().length()-1);
				    		duration = Calendar.getInstance().getTimeInMillis();
							try {
								MakeEnvironment makeEnvironment = new MakeEnvironment(temporaryDirectory, destinationFile.getName());
								makeEnvironment.start();
								while (makeEnvironment.isExecuting()) {
									Thread.sleep(50);
								}
								if (makeEnvironment.getExitValue() != 0) {
									error = true;
									textArea.append("Error exit value = " + makeEnvironment.getExitValue());
									textArea.append("\n");
								}
								if (makeEnvironment.getException() != null) {
									error = true;
									textArea.append(makeEnvironment.getException().getMessage());
									textArea.append("\n");
								}
							} catch (ExecutableException e) {
								error = true;
								textArea.append(e.getMessage());
								textArea.append("\n");
							} catch (InterruptedException e) {
								error = true;
								textArea.append(e.getMessage());
								textArea.append("\n");
							}
				    		duration = Calendar.getInstance().getTimeInMillis() - duration;
							textArea.append("["+((double)duration)/1000+"] ");
				    		textArea.repaint();
				    		textArea.setCaretPosition(textArea.getText().length()-1);
						}
						if (!error) {
							textArea.append("[Verifier] ");
				    		textArea.repaint();
				    		textArea.setCaretPosition(textArea.getText().length()-1);
				    		duration = Calendar.getInstance().getTimeInMillis();
							try {
								Verifier verifier = new Verifier(temporaryDirectory, destinationFile.getName());
								verifier.start();
								while (verifier.isExecuting()) {
									Thread.sleep(250);
							    	progressBarVerifier.setValue(verifier.getPercentage());
								}
								if (verifier.getExitValue() != 0) {
									error = true;
									textArea.append("Error exit value = " + verifier.getExitValue());
									textArea.append("\n");
								}
								if (verifier.getException() != null) {
									error = true;
									textArea.append(verifier.getException().getMessage());
									textArea.append("\n");
								}
							} catch (ExecutableException e) {
								error = true;
								textArea.append(e.getMessage());
								textArea.append("\n");
							} catch (InterruptedException e) {
								error = true;
								textArea.append(e.getMessage());
								textArea.append("\n");
							}
				    		duration = Calendar.getInstance().getTimeInMillis() - duration;
							textArea.append("["+((double)duration)/1000+"] ");
				    		textArea.repaint();
				    		textArea.setCaretPosition(textArea.getText().length()-1);
						}
						textArea.append("\n");
						textArea.append("           : ");
			    		textArea.repaint();
			    		textArea.setCaretPosition(textArea.getText().length()-1);
			    		progressBarVerifier.setValue(0);
						for (int i = 0; i < wfe.length; i++){
							if (!error && !WorkFileExtension.getClassName(wfe[i].toString()).equals("?")) {
								fileName = article.getAid().toLowerCase() + "."+ wfe[i];
								if ((i+1)%8 == 0) {
									textArea.append("\n");
									textArea.append("           : ");
								}
								textArea.append(wfe[i] + " ");
								File file = new File(temporaryDirectory.getFile(), fileName);
								if (file.exists()){
									check = FileWork.check(file, wfe[i].toString());
						    		if (!check.equals("")) {
						    			error = true;
										textArea.append("\n");
										textArea.append("[ERROR] ");
										textArea.append("\n");
										textArea.append(check);
										textArea.append("\n");
						    		} else {
										textArea.append("[OK] ");
						    		}
								} else {
									if (!file.getName().endsWith(".dfs") &&
											!file.getName().endsWith(".eid") &&
											!file.getName().endsWith(".esh") &&
											!file.getName().endsWith(".eth")) {
						    			error = true;
										textArea.append("\n");
										textArea.append("[ERROR] : File "+file.getName()+" is not present.");
										textArea.append("\n");
									}
								}
							}
						}
						textArea.append("\n");
			    		textArea.repaint();
			    		textArea.setCaretPosition(textArea.getText().length()-1);
				    	progressBarMML.setValue(progress);
				    	progressBarMML.repaint();
				    	if (testFrame.isClosed()) {
				    		error = true;
				    	}
		    		}
		    	}
			} 
			catch (Exception e) {
				textArea.append("\n");
	    		textArea.append(fileName);
	    		textArea.append(" -> Error");
				textArea.append("\n");
				textArea.append(e.getMessage());
				textArea.append("\n");
	    		textArea.repaint();
	    		textArea.setCaretPosition(textArea.getText().length()-1);
			}
			textArea.append("\n");
			textArea.repaint();
			textArea.setCaretPosition(textArea.getText().length()-1);
	    	progressBarMML.setValue(0);
			button.setEnabled(true);
		}
		
	}
	
}
